package com.topica;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.app.Dialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.topica.adapter.QuestionAdapter;
import com.topica.database.DataBaseHelper;
import com.topica.network.SendMark;
import com.topica.network.callback.OnSendMarkListener;
import com.topica.object.QuestionItem;
import com.topica.object.QuizItem;
import com.topica.object.QuizLogItem;
import com.topica.pager.callback.OnChooseAnswerListener;
import com.topica.util.Util;

public class TopicaQuiz extends FragmentActivity implements
		OnPageChangeListener, OnChooseAnswerListener, OnClickListener,
		OnSendMarkListener {

	private ViewPager pager;
	private QuestionAdapter adapter;
	public static final String LIST_QUESTION = "com.topica.TopicaDetailCourse.LIST_WEEK";
	public static final String QUIZ_ITEM = "com.topica.TopicaDetailCourse.QUIZ_ITEM";
	public static final String WEEK_ID = "com.topica.TopicaDetailCourse.WEEK_ID";
	private static final String TAG = "TopicaQuiz";
	private ArrayList<QuestionItem> data;
	private Button finishTest;
	private QuizItem quizItem;
	private String strPreTitleMarkReward;
	private TextView txtTimer;
	private CountDownTimer timer;
	private int weekId;

	private String startTime;
	private String endTime;
	private boolean isStarted = false;
	private QuizLogItem quizLogItem;
	private int totalPractice;

	private LinearLayout layoutInfo;
	private TextView txtQuizName;
	private TextView txtTimePractice;

	private int totalQuiz;
	private TextView titlePaging;
	

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_quiz);

		data = (ArrayList<QuestionItem>) getIntent().getExtras()
				.getSerializable(LIST_QUESTION);
		totalQuiz = data.size();

		quizItem = (QuizItem) getIntent().getExtras()
				.getSerializable(QUIZ_ITEM);
		weekId = getIntent().getExtras().getInt(WEEK_ID);
		DataBaseHelper db = new DataBaseHelper(this);
		int times = db.getPracticeTime(String.valueOf(weekId));

		titlePaging = (TextView) findViewById(R.id.pagingQuestion);
		
		layoutInfo = (LinearLayout) findViewById(R.id.layout_info);
		txtQuizName = (TextView) findViewById(R.id.txtQuizName);
		txtQuizName.setText(quizItem.getName());
		txtTimePractice = (TextView) findViewById(R.id.txtTimePractice);
		times = 4 - times;
		txtTimePractice.setText(getString(R.string.title_times_practice) + " "
				+ times);
		pager = (ViewPager) findViewById(R.id.pager);
		finishTest = (Button) findViewById(R.id.btnFinishQuiz);
		txtTimer = (TextView) findViewById(R.id.timer);
		adapter = new QuestionAdapter(getSupportFragmentManager(), data);
		pager.setAdapter(adapter);
		strPreTitleMarkReward = getResources().getString(
				R.string.title_pre_mark_reward);
		pager.setOnPageChangeListener(this);
		pager.setVisibility(View.INVISIBLE);
		finishTest.setOnClickListener(this);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int position) {
		titlePaging.setText(""+(position + 1)+"/"+ totalQuiz);
		
		adapter.getQuestionPager(position).onPageChange();
	}

	@Override
	public void onChooseAnswerListener(int indexQuestion, int indexAnswer,
			int idAnswer) {
		data.get(indexQuestion).setAnswer(indexAnswer);
		data.get(indexQuestion).setAnswerIdChoice(idAnswer);
	}

	@Override
	public void onClick(View v) {
		Button button = (Button) v;
		if (button
				.getText()
				.toString()
				.equalsIgnoreCase(
						getResources().getString(R.string.title_start))) {
			layoutInfo.setVisibility(View.GONE);
			button.setText(R.string.title_finish_quiz);
			pager.setVisibility(View.VISIBLE);
			titlePaging.setVisibility(View.VISIBLE);
			titlePaging.setText("1/" + totalQuiz);
			// tru so lan
			totalPractice = updatePracticeTime(String.valueOf(weekId));
			isStarted = true;
			long currentTime = System.currentTimeMillis();
			startTime = Util.convertCurrenttimeToDate(currentTime);
			int quizTime = quizItem.getTime();
			int quizTimeMillis = quizTime * 60 * 1000;
			timer = new CountDownTimer(quizTimeMillis, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					txtTimer.setText(Util.displayCountdown(millisUntilFinished));
					// System.out.println("left " + (millisUntilFinished));
				}

				@Override
				public void onFinish() {
					System.out.println("finish");
					txtTimer.setText("00:00:00");
					showMarkReward();
					isStarted = false;
				}
			};
			timer.start();
		} else {
			timer.cancel();
			showMarkReward();
		}
	}

	private int updatePracticeTime(String weekId) {
		DataBaseHelper db = new DataBaseHelper(TopicaQuiz.this);
		int times = db.getPracticeTime(weekId);
		times = times - 1;
		db.updatePracticeTime(weekId, times);
		// }
		return times;
	}

	@Override
	public void onCorrectAnswer(int indexQuestion, int correctAnswer) {
		data.get(indexQuestion).setCorrectAnswer(correctAnswer);
	}

	private void showDialogMark(String totalMarkReward) {
		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.dialog_mark);

		dialog.setTitle(getString(com.topica.R.string.title_summary_finish_quiz));

		String preTimeOpen = getResources().getString(R.string.title_open_time);
		String preTimeClose = getResources().getString(
				R.string.title_close_time);
		String preTimePractice = getResources().getString(
				R.string.title_number_practice);

		TextView quizName = (TextView) dialog.findViewById(R.id.quizName);
		quizName.setText("" + quizItem.getName());

		TextView text = (TextView) dialog.findViewById(R.id.txtMarkReward);
		TextView textOpen = (TextView) dialog
				.findViewById(R.id.title_time_open);
		TextView textClose = (TextView) dialog
				.findViewById(R.id.title_time_close);
		TextView textTimePrac = (TextView) dialog
				.findViewById(R.id.title_number_practice);

		textOpen.setText(preTimeOpen + ": " + quizItem.getTimeOpen());
		textClose.setText(preTimeClose + ": " + quizItem.getTimeClose());
		totalPractice = 3 - totalPractice;
		textTimePrac.setText(preTimePractice + ": " + totalPractice);
		text.setText(strPreTitleMarkReward + " " + totalMarkReward);
		Button dialogButton = (Button) dialog.findViewById(R.id.btnSendMark);

		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				SendMark mark = new SendMark(TopicaQuiz.this, quizLogItem);
				mark.setOnSendMarkListener(TopicaQuiz.this);
				mark.execute();
			}
		});

		// Button closeButton = (Button)
		// dialog.findViewById(R.id.btnCloseDialog);
		// closeButton.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// dialog.dismiss();
		// finish();
		// }
		// });
		dialog.show();
	}

	private void showMarkReward() {
		float markPerSentence = 10 / (float) quizItem.getNumberQuestion();
		float totalMark = 0;
		for (QuestionItem item : data) {
			if (item.getAnswerChoice() == item.getCorrectAnswer()) {
				totalMark += markPerSentence;
			}
		}

		long currentTime = System.currentTimeMillis();
		DecimalFormat df = new DecimalFormat("#.##");
		quizLogItem = new QuizLogItem();
		quizLogItem.setRealMark(totalMark);
		String strMark = df.format(totalMark);
		endTime = Util.convertCurrenttimeToDate(currentTime);
		DataBaseHelper baseHelper = new DataBaseHelper(getApplicationContext());
		int userId = Integer.valueOf(((TopicaApplication) getApplication())
				.getUserId());
		quizLogItem.setEnd_time(endTime);
		quizLogItem.setStart_time(startTime);
		quizLogItem.setUser_id(userId);
		quizLogItem.setMark(strMark);
		quizLogItem.setUser_choice(getAnswerChoice());
		quizLogItem.setId(quizItem.getId());
		quizLogItem.setQuizId(quizItem.getQuizId());
		baseHelper.insertQuizLog(quizLogItem);

		showDialogMark(strMark);
	}

	private String getAnswerChoice() {
		StringBuilder builder = new StringBuilder();
		for (int i = 0, n = data.size(); i < n; i++) {
			builder.append(data.get(i).getAnswerChoice());
			if (i != n - 1) {
				builder.append(",");
			}
		}
		return builder.toString();
	}

	@Override
	public void onBackPressed() {
		if (isStarted) {
			Toast.makeText(TopicaQuiz.this, R.string.unfinish,
					Toast.LENGTH_SHORT).show();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (timer != null) {
			timer.cancel();
		}
	}

	@Override
	public void onSendMarkDone() {
		// String titleSendMarkOK = getResources().getString(
		// R.string.title_send_mark_ok);
		// Toast.makeText(getApplicationContext(), titleSendMarkOK,
		// Toast.LENGTH_SHORT).show();
		
		finish();
	}

	@Override
	public void onSendMarkFail() {
		// String titleSendMark = getResources().getString(
		// R.string.title_send_mark_fail);
		// Toast.makeText(getApplicationContext(), titleSendMark,
		// Toast.LENGTH_SHORT).show();
		finish();
	}

}
